package online.hxstart.code.concurrent.chapter05;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.IntStream;

/**
 * @author huxing
 * @date 19-5-31 星期五 下午3:45
 * @describe
 */
public class BooleanLockTest {

  private final Lock lock = new BooleanLock();

  private void syncMethod() {
    try {
      lock.lock();
      int randomInt = new Random().nextInt(10);
      System.out.println(Thread.currentThread() + " get the lock .");
      TimeUnit.SECONDS.sleep(randomInt);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  private void syncMethodTimeoutable() {
    try {
      lock.lock(1000);
      System.out.println(Thread.currentThread() + " get the lock .");
      int randomInt = new Random().nextInt(20);
      TimeUnit.SECONDS.sleep(randomInt);
    } catch (InterruptedException | TimeoutException e) {
      e.printStackTrace();
    } finally {
      lock.unlock();
    }
  }

  public static void main(String[] args) throws InterruptedException {
    BooleanLockTest test = new BooleanLockTest();

    new Thread(test::syncMethod).start();
    TimeUnit.MILLISECONDS.sleep(2);
    Thread t1 = new Thread(test::syncMethodTimeoutable, "t1");
    t1.start();
    Thread t2 = new Thread(test::syncMethod, "t2");
    t2.start();
    TimeUnit.MILLISECONDS.sleep(10);
    t2.interrupt();

    IntStream.range(0, 10).mapToObj(i -> new Thread(test::syncMethod))
        .forEach(Thread::start);
  }
}
